#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>

const int N = 6e5 + 5, M = 1e6 + 5, inf = 0x3f3f3f3f;
int n, m, uid, vis[N], id[N], dis[N];
int e_cnt, heads[N];

struct Edge {
  int v, nxt, w;
} e[M << 1];

inline void add(int u, int v, int w) {
  e[++e_cnt].v = v, e[e_cnt].nxt = heads[u], heads[u] = e_cnt, e[e_cnt].w = w;
}

std::vector<std::pair<int, int> > vec[1000005];
std::queue<int> q;

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("testdata.in", "r", stdin);
  freopen("testdata.out", "w", stdout);
#else
  freopen("transfer.in", "r", stdin);
  freopen("transfer.out", "w", stdout);
#endif
#endif

  scanf("%d%d", &n, &m);
  uid = n;
  for (int i = 1, u, v, w; i <= m; ++i) {
    scanf("%d%d%d", &u, &v, &w);
    vec[w].push_back(std::make_pair(u, v));
  }
  for (int i = 1; i <= 1000000; ++i)
    for (auto &j : vec[i]) {
      int x = j.first, y = j.second;
      if (vis[x] != i) vis[x] = i, id[x] = ++uid, add(uid, x, 0), add(x, uid, 1);
      if (vis[y] != i) vis[y] = i, id[y] = ++uid, add(uid, y, 0), add(y, uid, 1);
      add(id[x], id[y], 0);
      add(id[y], id[x], 0);
    }
  memset(dis, 0x3f, sizeof(dis));
  memset(vis, 0, sizeof(vis));
  q.push(1);
  dis[1] = 0, vis[1] = 1;
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    for (int i = heads[u], v; i; i = e[i].nxt)
      if (dis[u] + e[i].w < dis[v = e[i].v]) {
        dis[v] = dis[u] + e[i].w;
        if (!vis[v]) {
          vis[v] = 1;
          q.push(v);
        }
      }
  }
  if (dis[n] == inf) puts("-1");
  else
    printf("%d\n", dis[n]);
  return 0;
}
